package com.rgs.base.springboot;

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;

/**
 * @author Ren Gaoshuai
 * @ClassName AbstractImportSelector
 * @Description 自定义类选择加载器
 * @date 2021-12-27 21:37
 **/
public abstract class AbstractImportSelector implements ImportSelector {

    /**
     * 返回想要被spring扫描的包
     * @return
     */
    protected abstract String[] getPackageList();

    /**
     * 返回想要被spring加载的类
     * @return
     */
    protected Class<?>[] getClassList() {
        return new Class[0];
    }

    /**
     * 该方法返回全路径类名，会被加载到spring中
     * @param importingClassMetadata
     * @return
     */
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        List<Class<?>> classes = SpringBootClassUtil.getClasses(
                Arrays.asList(this.getPackageList())
        );
        classes.addAll(Arrays.asList(getClassList()));
        return classes.stream().filter(q ->
                {
                    Annotation annotation = AnnotationUtils.findAnnotation(q, Component.class);
                    return annotation != null;
                }
        ).map(Class::getName).toArray(String[]::new);
    }
}
